<?php
/**
 * $items = array("here" => "now");
 * $moreitems = array("this" => "that");
 * $theArray = array("where" => "do we go", "here" => "we are today");
 * echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';
 * print_r($theArray);
 * 
 * Yields:
 * 4 is the size of $theArray.
 * Array
 * (
 *     [where] => do we go    
 *     [here] => now
 *     [this] => that
 *     [five] =>
 * )
 * 
 */
function array_push_assoc(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
           }
       }else{
           $arr[$arg] = "";
       }
   }
}

function show_msg_if_exists(){
	global $alert;
	if($alert['error'] == 1){
		include_once COMPONENT_PATH.'views/error.html.php';
	}
}

function get_date_from_str($datestr){
	return Date("Y-m-d", strtotime($datestr));
}

function get_string_from_date($date){
	return Date("m/d/Y", strtotime($date));
}

/**
 * @param $input - name of the image input field
 * @param $target - the path of the folder where the images have to be uploaded 
 * @return array
 * resizes an image and uploads
 */
function upload_image($input, $target){         // resizes image and uploads
	$uploaded_image = array();
	$uploaded_image['error'] = 0;
	
	$file_extensions_allowed = array('jpg', 'jpeg', 'gif', 'png');
	$file_size_limit = 500; // in KB
	$img_thumb_width = 100;  // required dimension
	$img_display_width = 500;
	$images_path = $target;
	$thumbnails_path = $target."thumbnails/";
	$originals_path = $target."original_imgs/";
	
	$file_size_limit *= 1000;
	$extlimit = "yes"; 
	$limitedext = $file_extensions_allowed;
	$file_type = $_FILES[$input]['type'];
	$file_name = $_FILES[$input]['name'];
	$file_size = $_FILES[$input]['size'];
	$file_tmp = $_FILES[$input]['tmp_name'];
	$ext = get_ext(basename($_FILES[$input]['name']));
	$ext = strtolower($ext);
	if(($extlimit=="yes")&&(!in_array($ext,$limitedext))){
		$uploaded_image['error'] = 1;
		$uploaded_image['msg'] = "Please upload a valid file.(File types allowed - jpg,jpeg,gif,png)";
		$uploaded_image['ext'] = $file_type;
	}
	else{
		if($file_size>=$file_size_limit){
			$uploaded_image['error'] = 1;
			$uploaded_image['msg'] = "Your file size exceeds the maximum size limit(maximum ".$file_size_limit/1000 . " KB)";
		}
		else{
			$image_name = substr($file_name, 0, strrpos($file_name,"."))."_".time().".".$ext;
			$images_path = $images_path.$image_name;
			$thumbnails_path = $thumbnails_path."thumbnail_".$image_name;
			$originals_path = $originals_path.$image_name;
			$ThumbWidth = $img_thumb_width;//parameter to be changed
			$dispWidth = $img_display_width;
			if($file_size){
				if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
					$new_img=imagecreatefromjpeg($file_tmp);
				}
				elseif($file_type == "image/x-png" || $file_type == "image/png"){
					$new_img=imagecreatefrompng($file_tmp);
				}
				elseif($file_type == "image/gif"){
					$new_img=imagecreatefromgif($file_tmp);
				}
				list($width,$height) = getimagesize($file_tmp);
				$imgratio = $width/$height;
				if($imgratio>1){ //parameter to be changed
					$newwidth=$ThumbWidth;
					$newwidth_disp = $dispWidth;
					$newheight=$ThumbWidth/$imgratio;
					$newheight_disp = $dispWidth/$imgratio;
				}
				else{
					$newheight=$ThumbWidth;
					$newheight_disp = $dispWidth;
					$newwidth=$ThumbWidth*$imgratio;
					$newwidth_disp = $dispWidth*$imgratio;
				}
				if(function_exists(imagecreatetruecolor)){
					$thumb_img = imagecreatetruecolor($newwidth,$newheight);
					$disp_img = imagecreatetruecolor($newwidth_disp, $newheight_disp);
				}
				else{
					die("Error:Please make sure you have GD library version 2+");
				}
				imagecopyresized($thumb_img,$new_img,0,0,0,0,$newwidth,$newheight,$width,$height);
				imagecopyresized($disp_img,$new_img,0,0,0,0,$newwidth_disp,$newheight_disp,$width,$height);
				ImageJpeg($new_img,$originals_path);
				ImageJpeg($thumb_img,$thumbnails_path);
				ImageJpeg($disp_img,$images_path);
				ImageDestroy($thumb_img);
				ImageDestroy($new_img);
				imagedestroy($disp_img);
			}
			$uploaded_image['name'] = $file_name;
			$uploaded_image['modified_name'] = $image_name;
			$uploaded_image['path'] = $images_path;
			$uploaded_image['thumbnails_path'] = $thumbnails_path;
			$uploaded_image['originals_path'] = $originals_path;
		}
	}
	return $uploaded_image;
}

/**
* @param file_name
* @return extension
* used to get the extension of the file to be uploaded
*/
function get_ext($name){
	$arr=explode(".",$name);
	$ext=end($arr);
	return$ext;
}

function delete_selected_items($ids_to_be_deleted, $obj){
	if(!empty($ids_to_be_deleted)){
		mysql_query("BEGIN");
		foreach($ids_to_be_deleted as $id){
			$delete_items_msg = $obj->delete_row_query("DELETE FROM `".$obj->get_table_name()."` WHERE `id` = '".$id."'");
			if($delete_items_msg['error'] == 1) break;
		}
		if($delete_items_msg['error'] == 1){
			mysql_query("ROLLBACK");
		}
		else{
			mysql_query("COMMIT");
		}
		return $delete_items_msg;
	}
}

function confirm_selected_items($ids_to_be_confirmed, $obj, $confirm){
	if(!empty($ids_to_be_confirmed)){
		mysql_query("BEGIN");
		foreach($ids_to_be_confirmed as $id){
			$confirm_items_msg = $obj->insert_row_query("UPDATE `".$obj->get_table_name()."` SET `confirmed` = '".$confirm."' WHERE `id` = '".$id."'");
			if($confirm_items_msg['error'] == 1) break;
		}
		if($confirm_items_msg['error'] == 1){
			mysql_query("ROLLBACK");
		}
		else{
			//mysql_query("COMMIT");
			mysql_query("ROLLBACK");
		}
		return $confirm_items_msg;
	}
}

function publish_selected_items($ids_to_be_published, $obj, $publish){
	if(!empty($ids_to_be_published)){
		mysql_query("BEGIN");
		foreach($ids_to_be_published as $id){
			$publish_items_msg = $obj->insert_row_query("UPDATE `".$obj->get_table_name()."` SET `published` = '".$publish."' WHERE `id` = '".$id."'");
			if($publish_items_msg['error'] == 1) break;
		}
		if($publish_items_msg['error'] == 1){
			mysql_query("ROLLBACK");
		}
		else{
			mysql_query("COMMIT");
		}
		return $publish_items_msg;
	}
}

function redirectToHTTPS(){
  if($_SERVER['HTTPS']!="on")
  {
     $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
     header("Location:$redirect");
  }
}

function get_price($start_date, $end_date, $intervals){
	$diff = dateDiff("/", $end_date, $start_date);
	$price = 0;
	$date = get_string_from_date($start_date);
	for($i = 0; $i < $diff+1; $i++){
		foreach($intervals as $interval){
			if($date >= get_string_from_date($interval->startdate) && $date <= get_string_from_date($interval->enddate)){
				$price = $price + $interval->price;
			}
		}
		$date = add_date($date, 1);
	}
	return $price;
}

function add_date($date, $no_of_days){
	return date("m/d/Y", strtotime( $date . " +".$no_of_days." day"));
}

function dateDiff($dformat, $endDate, $beginDate){
    $date_parts1=explode($dformat, $beginDate);
    $date_parts2=explode($dformat, $endDate);
    $start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
    $end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
    return $end_date - $start_date;
}
?>